package com.sz.security;

import com.sz.pojo.Permission;
import com.sz.pojo.Role;
import com.sz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.sz.pojo.User loginUser =userService.findByUsername(username);
        if (null==loginUser){
            return null;
        }
        List<GrantedAuthority> authorities =new ArrayList<>();

        Set<Role> roles = loginUser.getRoles();
        if(!CollectionUtils.isEmpty(roles)){
            // 有角色
            for (Role role : roles) {
                // 使用关键以ROLE_开头, 将来可以使用hasRole表达
                authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                //授予权限 hasAuthority
                Set<Permission> permissions = role.getPermissions();
                if(!CollectionUtils.isEmpty(permissions)){
                    // 角色下有权限
                    for (Permission permission : permissions) {
                        //授予权限
                        authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }


        return new User(username,loginUser.getPassword(),authorities);
    }
}
